<template>
  <view class="order-list-content">
    <cc-newsTabs :tabArr="tabArr" @tabChange="tabChange"></cc-newsTabs>
    <view class="order-list">
      <!-- <wu-loading-icon :show="vShow" size="50" textSize="20" text="加载中" :vertical="true"></wu-loading-icon> -->
      <!-- <scroll-view scroll-y="true" class="list-content"> -->
      <view scroll-y="true" class="list-content">
        <template v-for="(it,index) in list" :key="it.object_id">
          <view class="list-content-item">
            <view class="item-top">
              <text class="order-id">订单编号: {{it.object_id}}</text>
              <text class="order-state">{{it.statusHint}}</text>
            </view>

            <view class="item-center">
              <scroll-view scroll-x="true" class="item-center-scroll" @touchmove.stop.prevent>
                <template v-for="(sub,index) in it.items" :key="index">
                  <view class="center-scroll-item">
                    <image class="item-center-img" :src="sub.img" mode="aspectFill"></image>
                    <view class="scroll-item-info">
                      <text class="info-name">{{sub.name}}</text>
                      <text>{{displayPrice(sub.price)}}</text>
                    </view>

                  </view>
                </template>
              </scroll-view>

              <view class="item-bottom-end">
                <text class="bottom-end-amount">{{displayPrice(it.real_price)}}</text>
                <text class="bottom-end-total">共{{it.amount}}份</text>
              </view>
            </view>

            <view class="item-bottom">
              <text>下单：{{it.created_at}}</text>
              <text class="item-bottom-sort">序号：{{`${it.number}`}}</text>
            </view>

          </view>
        </template>
      </view>
    </view>
    <uni-load-more :status="listStatus" v-if="isLoadDisplay"></uni-load-more>
  </view>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue';
  import { onReady, onLoad, onReachBottom } from '@dcloudio/uni-app';
  import { queryOrders } from "@/common/utils/requestModel.js"
  import { UserInfo, DataInfo } from '@/common/models/BaseData.ts'
  import { displayPrice, loadingShow, loadingHide } from "@/common/utils/public.ts";
  import dayjs from 'dayjs';


  class OrderItems {
    object_id : string
    status : number
    device_id : string
    real_price : number
    updated_at : string
    created_at : string
    number:string
    items : Array<ItemProduct>
    constructor(
      object_id : string,
      status : number,
      device_id : string,
      real_price : number,
      updated_at : string,
      created_at : string,
      number:string,
      items : Array<ItemProduct>
    ) {
      this.object_id = object_id
      this.status = status
      this.device_id = device_id
      this.real_price = real_price
      this.updated_at = updated_at
      this.created_at = created_at
      this.number = number
      this.items = items
      this.setStatusHint()
      this.setAmount()
    }

    amount : number = 0
    setAmount() {
      this.amount = this.items.reduce(function (a, b) { return a + b.quantity; }, 0);
    }

    statusHint : string = ""

    /*      STATUS_PAY_WAIT = 0
          STATUS_PAYING = 1
          STATUS_PAY_FAILED = 2
          STATUS_CANCELLED = 3
          STATUS_PAY_SUCCESS = 4
          STATUS_DELIVERY_START = 5
          STATUS_DELIVERY_SUCCESS = 6
          STATUS_REFUNDED = 7
          STATUS_DELIVERY_FAILED = 8
          STATUS_PICK_SUCCESS = 9
          STATUS_PICK_FAILED = 10 */
    setStatusHint() {
      if (this.status == 4) {
        this.statusHint = "已支付"
      } else if (this.status == 5 || this.status == 6 || this.status == 8) {
        this.statusHint = "提货中"
      } else if (this.status == 9) {
        this.statusHint = "已完成"
      } else if (this.status == 7) {
        this.statusHint = "已退款"
      } else if (this.status == 10) {
        this.statusHint = "提货失败"
      } else {

      }
    }

  }

  class ItemProduct {
    img : string
    name : string
    price : number
    quantity : number
    constructor(
      img : string,
      name : string,
      price : number,
      quantity : number
    ) {
      this.img = img
      this.name = name
      this.price = price
      this.quantity = quantity
    }

  }

  // const vShow = ref(false)
  // const status = ref("no-more")
  onLoad(() => {

  })
  onReady(() => {
    console.log('onReady--')
    requestOrders(1, null)
  })

  onReachBottom(() => {
    console.log('onReachBottom--')

    if (orderInfo.value.pages > 1 && orderInfo.value.page < orderInfo.value.pages) {
      listStatus.value = "loading"
      requestOrders((orderInfo.value.page + 1), null)
    }

  })

  const isLoadDisplay = computed(() => {
    listStatus.value = "no-more"
    if (orderInfo.value != null) {
      if (orderInfo.value.pages > 1 && orderInfo.value.pages > orderInfo.value.page) {
        listStatus.value = "more"
        // return true
      } else {
        /* if (orderInfo.value.orders.length <= 4) {
          return false
        } else {
          return true
        } */
      }
      return true
    } else {
      return false
    }
  })

  const listStatus = ref("no-more")

  //初始化数据
  const tabArr = ref([{
    name: '全部订单',
    id: '1',
  },
  // {
  //   name: '待付款',
  //   id: '2'
  // },
  // {
  //   name: '待发货',
  //   id: '3'
  // },
  {
    name: '已完成',
    id: '9'
  }])
  /**
   * 时间戳转日期格式（基于 day.js）
   * @param timestamp 时间戳（秒或毫秒）
   * @param format 格式，例如 'YYYY-MM-DD HH:mm:ss'
   * @returns 格式化后的日期字符串
   */
  function formatDateWithDayjs(timestamp : number, format : string = 'YYYY-MM-DD HH:mm:ss') : string {
    // 处理时间戳单位
    const ts = timestamp < 1e12 ? timestamp * 1000 : timestamp;
    return dayjs(ts).format(format);
  }
  let cIndex = 0
  // tab标签栏改变事件
  function tabChange(currentIndex) {
    if (cIndex == currentIndex) return
    cIndex = currentIndex
    let item = tabArr.value[currentIndex]
    console.log("点击分类:", item)
    let status = null
    if (currentIndex != 0) {
      status = Number(item.id)
    }
    requestOrders(1, status)
    // uni.showModal({
    //   title: "当前选择序列",
    //   content: "当前选择序列 = " + { ...item }
    // })
  }


  const list = ref<Array<OrderItems>>([])
  const orderInfo = ref<DataInfo<OrderItems>>(null)

  async function requestOrders(page : number, status : number) {
    let parmas = {}
    if (page != null) {
      parmas.page = page
    }
    if (status != null) {
      parmas.status = status
    }

    queryOrders(parmas).then(result => {
      console.log("订单列表信息:", result)
      if (result.data.code != undefined) {
        return
      }
      let orderItems = new Array<OrderItems>()
      for (const item of result.data.orders) {
        let itemProducts = new Array<ItemProduct>()
        for (const product of item.items) {
          itemProducts.push(new ItemProduct(
            product.img,
            product.name,
            product.price,
            product.quantity
          ))
        }
        let updatedAt = "0000-00-00"
        let createdAt = "0000-00-00"

        try {
          updatedAt = formatDateWithDayjs(item.updated_at)
          createdAt = formatDateWithDayjs(item.created_at)
        } catch (error) {
          console.log("点单日期转换异常", error)
        }
        let n = item.number
        console.log("订单序号：",n)
        orderItems.push(new OrderItems(
          item.object_id,
          item.status,
          item.device_id,
          item.real_price,
          updatedAt,
          createdAt,
          n,
          itemProducts
        ))
      }
      orderInfo.value = new DataInfo(
        result.data.page,
        result.data.per_page,
        result.data.total,
        orderItems
      )
      list.value = orderItems
    }).catch(e => {

    })

  }

  function switchPage(state : number) {
    let filters = orderInfo.value.orders.filter((c, index, arr) => { c.status == state })
    list.value = filters
  }
</script>

<style lang="scss">
  .order-list-content {
    position: relative;
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
  }

  .order-list {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 90%;

    .list-content {
      position: absolute;
      width: 100%;
      height: 90%;
      padding: 20rpx;
      box-sizing: border-box;

      .list-content-item {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 500rpx;
        padding: 0 20rpx;
        margin-top: 20rpx;
        border-radius: 20rpx;
        background: $color-white;
        box-sizing: border-box;

        .item-top {
          display: inline-flex;
          justify-content: center;
          width: 100%;
          line-height: 100rpx;
          // padding: 0 20rpx;
          box-sizing: border-box;
          border-bottom: 1rpx solid #D8D8D8;

          .order-id {
            flex: 1;
            font-size: 25rpx;
          }

          .order-state {
            width: 90rpx;
            text-align: end;
            color: #FFB200;
            font-size: 25rpx;

          }
        }

        .item-center {
          display: inline-flex;
          width: 100%;
          height: 300rpx;
          padding: 10rpx 0;
          box-sizing: border-box;

          .item-center-scroll {
            height: 100%;
            flex: 1;

            .center-scroll-item {
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
              width: 160rpx;
              height: 100%;

              .item-center-img {
                width: 100%;
                height: 160rpx;
              }

              .scroll-item-info {
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                width: 100%;
                height: 100rpx;
                // padding: 10rpx 20rpx;
                box-sizing: border-box;

                .info-name {
                  width: 100%;
                  padding: 5rpx 0;
                  text-overflow: ellipsis;
                  overflow: hidden;
                  white-space: nowrap;
                }
              }

            }




          }


          .item-bottom-end {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            width: 170rpx;
            height: 100%;

            // background: #FFB200;
            .bottom-end-amount {
              font-size: 40rpx;
            }

            .bottom-end-total {
              font-size: 30rpx;
              color: #3D3D3D;
            }
          }

        }

        .item-bottom {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          width: 100%;
          line-height: 90rpx;
          color: #3D3D3D;
          font-size: 30rpx;
          
          .item-bottom-sort{
            line-height: 90rpx;
            color: #a21a1a;
            font-size: 30rpx;
          }
        }
      }
    }

  }
</style>